﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using UserManage;
using Eb.MessageBox;
public partial class ucUserSearch : System.Web.UI.UserControl
{

    UserManager _userManager = new UserManager();
    string basePath = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        btnAddUser.Attributes.Add("onmouseover", "this.style.backgroundColor='#00B5F0'");
        btnAddUser.Attributes.Add("onmouseout", "this.style.backgroundColor='#008FBF'");
        btnSearch.Attributes.Add("onmouseover", "this.style.backgroundColor='#00B5F0'");
        btnSearch.Attributes.Add("onmouseout", "this.style.backgroundColor='#008FBF'");
        btnAdvanced.Attributes.Add("onmouseover", "this.style.backgroundColor='#00B5F0'");
        btnAdvanced.Attributes.Add("onmouseout", "this.style.backgroundColor='#008FBF'");
        btnBack.Attributes.Add("onmouseover", "this.style.backgroundColor='#00B5F0'");
        btnBack.Attributes.Add("onmouseout", "this.style.backgroundColor='#008FBF'");
        btnAdvancedSearch.Attributes.Add("onmouseover", "this.style.backgroundColor='#00B5F0'");
        btnAdvancedSearch.Attributes.Add("onmouseout", "this.style.backgroundColor='#008FBF'");
        btnEditUser.Attributes.Add("onmouseover", "this.style.backgroundColor='#00B5F0'");
        btnEditUser.Attributes.Add("onmouseout", "this.style.backgroundColor='#008FBF'");
        btnDeleteUser.Attributes.Add("onmouseover", "this.style.backgroundColor='#00B5F0'");
        btnDeleteUser.Attributes.Add("onmouseout", "this.style.backgroundColor='#008FBF'");
        btnRoles.Attributes.Add("onmouseover", "this.style.backgroundColor='#00B5F0'");
        btnRoles.Attributes.Add("onmouseout", "this.style.backgroundColor='#008FBF'");

        basePath = "~/Modules/UserManager/";
      //  basePath = Server.MapPath();
        btnDeleteUser.Attributes.Add("OnClick", "return confirmDelete()");
        if (!IsPostBack)
        {
            Session["UserManager_UserSearch"] = "Latest";
            Search();
            //upnlAdvanceSearch.Visible = false;
            tblAdvance.Visible = false;
            InitializeDDL();
        }
    }

    //private string LastLoadedControl
    //{
    //    get
    //    {
    //        return ViewState["LastLoaded"] as string;
    //    }
    //    set
    //    {
    //        ViewState["LastLoaded"] = value;
    //    }
    //}

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //if (txtSearch.Text == string.Empty)
        //    Session["UserManager_UserSearch"] = "BlankSearch";
        //else
            Session["UserManager_UserSearch"] = txtSearch.Text.Trim();

        Search();
    }

    protected void btnAdvanced_Click(object sender, EventArgs e)
    {
       // upnlAdvanceSearch.Visible = true;
        tblSearch.Visible = false;
        tblAdvance.Visible = true;        
    }
    private void LoadUserControl(string ss)
    {
        string controlPath = ss;

      
    }
    protected void btnAddUser_Click(object sender, EventArgs e)
    {
        Session["UserManager_PersonalID"] = string.Empty;        
        Session["UserManager_Control"] = "UserManager/ucUserAdd.ascx";
        Session["UserManager_Edit"] = "User Add";
        Session["UserManager_Picture"] =string.Empty;       
        Response.Redirect("BusinessProcessAutomation.aspx");
        //phAddControls.Controls.Clear();
        //controlPath = basePath;
        //string path = controlPath + Session["UserManager_Control"];
        //LastLoadedControl = path;
        //UserControl uc = (UserControl)LoadControl(path);
        //phAddControls.Controls.Add(uc);
    }

    protected void btnDeleteUser_Click(object sender, EventArgs e)
    {
        Delete();
        Search();
    }

    protected void btnEditUser_Click(object sender, EventArgs e)
    {
        if (CheckSelection() == "Single Selected") //check whether a user is selected
        {
            Session["UserManager_Control"] = "UserManager/ucUserAdd.ascx";
            Session["UserManager_Edit"] = "User Edit";
            Response.Redirect("BusinessProcessAutomation.aspx");
        }
    }

    protected void btnRoles_Click(object sender, EventArgs e)
    {
        if (CheckSelection() =="Single Selected") //check whether a user is selected
        {
            Session["UserManager_Control"] = "UserManager/ucRoleDisplay.ascx";
            Response.Redirect("BusinessProcessAutomation.aspx");
        }
    }
    

    protected void rblCriteria_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (rblCriteria.SelectedItem.ToString() != "Date of Creation")
        {
            lblSearch.Text = rblCriteria.SelectedItem.ToString();
            txtCriteriaName.Enabled = true;
            ddlDateofCreation.Enabled = false;
            if (rblCriteria.SelectedItem.ToString() == "LoginID")
            {
                ddlRole.Enabled = false;
            }
            else
            {
                ddlRole.Enabled = true;
            }
        }
        else
        {
            txtCriteriaName.Enabled = false;
            ddlRole.Enabled = false;
            ddlDateofCreation.Enabled = true;
        }
    }
    protected void imbDateofCreation_Click(object sender, ImageClickEventArgs e)
    {
       // calDateofCreation.Visible = true;
    }
    protected void calDateofCreation_SelectionChanged(object sender, EventArgs e)
    {
      //  txtDateofCreation.Text = calDateofCreation.SelectedDate.ToShortDateString ();
      //  calDateofCreation.Visible = false;
    }
    protected void btnAdvancedSearch_Click(object sender, EventArgs e)
    {
        if (rblCriteria.SelectedIndex == -1)
        {
            Response.Write("<script>alert('Select Search Criteria')</script>");
            return;
        }
        if (((rblCriteria.SelectedItem.ToString() != "Date of Creation") & (txtCriteriaName.Text == string.Empty)) ||
            ((rblCriteria.SelectedItem.ToString() == "Date of Creation") & (txtDateofCreation.Text == string.Empty)))
            Session["UserManager_UserSearch"] = "BlankSearch";
        //if  ((rblCriteria.SelectedItem.ToString() == "Date of Creation") & (txtDateofCreation.Text == string.Empty))
        //    Session["UserManager_UserSearch"] = "BlankSearch";
        else if (rblCriteria.SelectedItem.ToString() == "Date of Creation")
            Session["UserManager_UserSearch"] = txtDateofCreation.Text;
        else
            Session["UserManager_UserSearch"] = txtCriteriaName.Text;
        AdvancedSearch();
    }

    protected void lnbUsers_Click1(object sender, EventArgs e)
    {
      
    }
    protected void lnbRoles_Click(object sender, EventArgs e)
    {
        Session["UserManager_Control"] = "ucRole.ascx";
        Response.Redirect("BusinessProcessAutomation.aspx");
    }

    protected void lnbUtilities_Click(object sender, EventArgs e)
    {
        Session["UserManager_Control"] = "ucSearchAddUtility.ascx";
        Response.Redirect("BusinessProcessAutomation.aspx");
    }
    protected void lnbPermissions_Click(object sender, EventArgs e)
    {
        Response.Redirect("AddPermission.aspx");
    }

    void Search()
    {
        try
        {
            //upnlAdvanceSearch.Visible = false;
            string toSearch;

            //  if (txtSearch.Text == string.Empty)

          
                DataSet ds = new DataSet();
                _userManager.SearchUser(Session["UserManager_UserSearch"].ToString(), out ds);
                gvwUserDetails.Visible = true;
                gvwUserDetails.DataSource = ds;
                //if (ds.Tables[0].Rows.Count > 0)
                //{
                gvwUserDetails.Columns[1].Visible = true;
                gvwUserDetails.DataBind();
                gvwUserDetails.Columns[1].Visible = false;
            //}
            //else
            //{
            //    gvwUserDetails.Visible = true;
            //    gvwUserDetails.EmptyDataText = "No Records Found";
            ////    Response.Write("<script>alert('No User Found !')</script>");
            //}

        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Search User Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }
    }


    void AdvancedSearch()
    {
        try
        {
            DataSet ds = new DataSet();
            SearchCriteria advanceSearch = new SearchCriteria();
            advanceSearch.SetCriteria = rblCriteria.SelectedItem.ToString();
            advanceSearch.CriteriaName = txtCriteriaName.Text;
            advanceSearch.Role = ddlRole.SelectedValue;
            advanceSearch.DateofCreation = txtDateofCreation.Text;
            advanceSearch.DateStatus = ddlDateofCreation.SelectedItem.ToString();

            bool res = _userManager.AdvancedUserSearch(advanceSearch, out ds);

            if (res == false)
                return;            
            gvwUserDetails.DataSource = ds;
            gvwUserDetails.Columns[1].Visible = true;
            gvwUserDetails.DataBind();
            gvwUserDetails.Columns[1].Visible = false;
        }

        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Search User Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }
    }

    void InitializeDDL()
    {
        try
        {
            ddlDateofCreation.Items.Clear();
            ddlDateofCreation.Items.Insert(0, "On");
            ddlDateofCreation.Items.Insert(1, "Before");
            ddlDateofCreation.Items.Insert(2, "After");

            DataSet ds = new DataSet();
            ds = _userManager.GetData("UserRolesList", string.Empty);
            ddlRole.Items.Clear();
            ddlRole.DataSource = ds;
            ddlRole.DataTextField = "UR_RoleName";
            ddlRole.DataValueField = "UR_RoleID";
            ddlRole.DataBind();
            ddlRole.Items.Insert(0, "Select");
        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Initialize DropDownList Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }
        
    }
    protected void gvwUserDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvwUserDetails.PageIndex = e.NewPageIndex;
        Search();
    }
    
    protected void lnbHome_Click(object sender, EventArgs e)
    {
        Response.Redirect("UserHome.aspx");
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        tblSearch.Visible = true;
        tblAdvance.Visible = false;
        Clear();
    }

    void Delete()
    {
        try
        {
            Session["UserManager_Edit"] = "User Delete";

            int index = 0;
            string[] personalID = new string[gvwUserDetails.Rows.Count];
            UserDetails userDetailsDelete = new UserDetails();
            for (int i = 0; i < gvwUserDetails.Rows.Count; i++)
            {
                CheckBox chkGrid = (CheckBox)(gvwUserDetails.Rows[i].Cells[0].FindControl("chkEditDelete"));
                if (chkGrid.Checked == true)
                {
                    personalID[index] = gvwUserDetails.Rows[i].Cells[1].Text;
                    index++;
                }
            }

            if (index == 0)
            {
                Response.Write("<script>alert('Select User')</script>");
                return;
            }
            //for (int i = 0; i <= index; i++)
            //{
            //    userDetailsDelete.UserID = personalID[i];
            //    _userSearch.DeleteUser(userDetailsDelete);
            //}
            string conditionDeleteRolesMap = "UM_UserID='" + personalID[0] + "'";
            string conditionDeletePermissionMap = "PM_ActorID='" + personalID[0] + "'";
            string conditionDeleteUserList = "UL_UserPersonalID='" + personalID[0] + "'";
            string conditionDeleteUser = "UD_UserPersonalID='" + personalID[0] + "'";
            //for (int i = 0; i <= index; i++)
            //{
            //    userDetailsDelete.UserID = personalID[i];
            //    _userSearch.DeleteUser(userDetailsDelete);
            //}
            for (int i = 1; i < index; i++)
            {
                conditionDeleteRolesMap = conditionDeleteRolesMap + "or UM_UserID='" + personalID[i] + "'";
                conditionDeletePermissionMap = conditionDeletePermissionMap + "or PM_ActorID='" + personalID[i] + "'";
                conditionDeleteUserList = conditionDeleteUserList + "or UL_UserPersonalID = '" + personalID[i] + "'";
                conditionDeleteUser = conditionDeleteUser + "or UD_UserPersonalID='" + personalID[i] + "'";
            }

            _userManager.DeleteUser(conditionDeleteRolesMap, conditionDeletePermissionMap, conditionDeleteUserList, conditionDeleteUser);
            Response.Write("<script>alert('Deleted Successfully !')</script>");
        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Delete User Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }
       
    }

    string CheckSelection()
    {
        string status = string.Empty;
        try
        {
            int count = 0, selectedRow = -1;            
            string[] ID = new string[gvwUserDetails.Rows.Count];

            for (int i = 0; i < gvwUserDetails.Rows.Count; i++)
            {
                CheckBox chkGrid = (CheckBox)(gvwUserDetails.Rows[i].Cells[0].FindControl("chkEditDelete"));
                if (chkGrid.Checked == true)
                {
                    ID[count] = gvwUserDetails.Rows[i].Cells[1].Text;
                    count++;
                    selectedRow = i;
                }
            }

            if (count == 0)
            {
                //Response.Write("<script>alert('Select a User/Role')</script>");
                MessageBox.Show("Select a User/Role");
                status = "None Selected";
                return status;
            }
            else if (count > 1)
            {
                //Response.Write("<script>alert('Select Single User/Role')</script>");
                MessageBox.Show("Select Single User/Role");

                status = "Multiple Selected";
            }
            else
            {
                status = "Single Selected";
            }
            //zzzzzz
            Session["UserManager_PersonalID"] = gvwUserDetails.Rows[selectedRow].Cells[1].Text;

            Session["UserManager_IDs"] = ID;
            Session["UserManager_selectedUsers"] = count;
        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Check Selection Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }
        return status;



        //for (int i = 0; i < gvwUserDetails.Rows.Count; i++)
        //{
        //    CheckBox chkGrid = (CheckBox)(gvwUserDetails.Rows[i].Cells[0].FindControl("chkEditDelete"));
        //    if (chkGrid.Checked == true)
        //    {
        //        count++;
        //        selectedRow = i;
        //    }
        //}

        //if (count == 0)
        //{
        //    Response.Write("<script>alert('Select a User')</script>");
        //    return false;
        //}
        //else if (count > 1)
        //{
        //    Response.Write("<script>alert('Select Single User')</script>");
        //    return false;
        //}

        //Session["UserManager_PersonalID"] = gvwUserDetails.Rows[selectedRow].Cells[1].Text;
        //return true;

        //for (int i = 0; i < gvwUserDetails.Rows.Count; i++)
        //{
        //    CheckBox chkGrid = (CheckBox)(gvwUserDetails.Rows[i].Cells[0].FindControl("chkEditDelete"));
        //    if (chkGrid.Checked == true)
        //    {                
        //        userIDs[count] = gvwUserDetails.Rows[i].Cells[1].Text;
        //        count++;
        //        //selectedRow = i;
        //    }
        //}

        //if (count == 0)
        //{
        //    Response.Write("<script>alert('Select a User')</script>");
        //    return false;
        //}
        //else if (count > 1)
        //{
        //    Response.Write("<script>alert('Select Single User')</script>");
        //    return false;
        //}
        //Session["UserManager_userIDs"] = userIDs;
        //Session["UserManager_selectedUsers"] = count;
        ////Session["UserManager_PersonalID"] = gvwUserDetails.Rows[selectedRow].Cells[1].Text;
        //return true;
    }

    void Clear()
    {
        try
        {
            rblCriteria.SelectedIndex = -1;
            txtCriteriaName.Text = string.Empty;
            ddlRole.SelectedIndex = 0;
            ddlDateofCreation.SelectedIndex = 0;
            txtDateofCreation.Text = string.Empty;
            //   calDateofCreation.Visible = false;
        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Clear Controls Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }
    }

    void EnableDelete()
    {

    }

    protected void gvwUserDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");

            e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");

        } 
       if(e.Row.RowType==DataControlRowType.EmptyDataRow)
           e.Row.CssClass = "grid-view-header";
        if (e.Row.RowType == DataControlRowType.Header)
            e.Row.CssClass = "grid-view-header";

        //Add CSS class on normal row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Normal)
            e.Row.CssClass = "grid-view-normal";

        //Add CSS class on alternate row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Alternate)
            e.Row.CssClass = "grid-view-alternate";
    }

    protected void gvwUserRoles_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");

            e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");

        }
        if (e.Row.RowType == DataControlRowType.EmptyDataRow)
            e.Row.CssClass = "grid-view-header";
        if (e.Row.RowType == DataControlRowType.Header)
            e.Row.CssClass = "grid-view-header";

        //Add CSS class on normal row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Normal)
            e.Row.CssClass = "grid-view-normal";

        //Add CSS class on alternate row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Alternate)
            e.Row.CssClass = "grid-view-alternate";
    }



    
   
}
